<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
      layout:decorate="~{layout/default}">
<head>
    <title>销售团队协作</title>
    <style>
        .collab-container { padding: 20px; }
        .team-card { background: #fff; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); padding: 15px; margin-bottom: 20px; }
        .member-avatar { width: 40px; height: 40px; border-radius: 50%; margin-right: 10px; display: flex; align-items: center; justify-content: center; background: #e9ecef; color: #495057; font-weight: bold; }
        .member-list { display: flex; flex-wrap: wrap; gap: 10px; }
        .member-item { display: flex; align-items: center; background: #f8f9fa; padding: 8px; border-radius: 20px; }
        .task-list { margin-top: 20px; }
        .task-item { padding: 12px; border-left: 3px solid #4285f4; background: #f8f9fa; margin-bottom: 10px; border-radius: 4px; }
        .task-header { display: flex; justify-content: space-between; }
        .task-priority-high { color: #d93025; }
        .task-priority-medium { color: #f29900; }
        .task-priority-low { color: #1a73e8; }
        .communication-container { margin-top: 20px; }
        .message-list { max-height: 300px; overflow-y: auto; }
        .message-item { padding: 10px; border-radius: 8px; margin-bottom: 10px; }
        .message-sent { background: #e3f2fd; margin-left: 30px; }
        .message-received { background: #f1f3f4; margin-right: 30px; }
        .team-performance { margin-top: 20px; }
        .performance-bar { height: 20px; background: #e0e0e0; border-radius: 10px; margin-top: 5px; }
        .performance-progress { height: 100%; border-radius: 10px; background: linear-gradient(90deg, #4285f4, #34a853); }
    </style>
</head>
<body>
    <div layout:fragment="content">
        <div class="content-header">
            <h1>销售团队协作</h1>
        </div>
        
        <div class="collab-container">
            <!-- 团队筛选 -->
            <div class="filter-section mb-4">
                <select id="team-select" class="form-control">
                    <option value="">选择团队</option>
                    <option th:each="team : ${teams}" th:value="${team.id}" th:text="${team.name}"></option>
                </select>
            </div>
            
            <!-- 团队信息 -->
            <div class="team-card">
                <h3 th:text="${currentTeam != null ? currentTeam.name : '请选择团队'}">团队名称</h3>
                <p>团队负责人: <strong th:text="${currentTeam != null && currentTeam.leader != null ? currentTeam.leader.realName : '未指定'}">未指定</strong></p>
                <div class="member-list">
                    <div th:if="${teamMembers == null || teamMembers.isEmpty()}" class="alert alert-info">暂无团队成员</div>
                    <div th:each="member : ${teamMembers}" class="member-item">
                        <div class="member-avatar" th:text="${member.user != null && member.user.realName != null ? member.user.realName.substring(0,1) : '?'}">头像</div>
                        <span th:text="${member.user != null ? (member.user.realName != null ? member.user.realName : member.user.username) + ' (' + member.role + ')' : '未知用户'}">成员名称</span>
                    </div>
                </div>
                
                <!-- 团队绩效 -->
                <div class="team-performance">
                    <h4>团队绩效</h4>
                    <div>
                        <span>目标达成率: 78%</span>
                        <div class="performance-bar">
                            <div class="performance-progress" style="width: 78%"></div>
                        </div>
                    </div>
                    <div class="mt-2">
                        <span>成交量: 24/30</span>
                        <div class="performance-bar">
                            <div class="performance-progress" style="width: 80%"></div>
                        </div>
                    </div>
                </div>
            </div>
            
            <!-- 团队任务 -->
            <div class="task-list">
                <h3>团队任务</h3>
                <div th:if="${teamTasks == null || teamTasks.isEmpty()}" class="alert alert-info">暂无团队任务</div>
                <div th:each="task : ${teamTasks}" class="task-item">
                    <div class="task-header">
                        <span><strong th:text="${task.name}">任务名称</strong></span>
                        <span th:class="${task.priority == 1 ? 'task-priority-high' : (task.priority == 2 ? 'task-priority-medium' : 'task-priority-low')}"
                              th:text="${task.priority == 1 ? '高优先级' : (task.priority == 2 ? '中优先级' : '低优先级')}">优先级</span>
                    </div>
                    <p>截止日期: <span th:text="${task.dueDate != null ? #temporals.format(task.dueDate, 'yyyy年MM月dd日') : '未设置'}">截止日期</span></p>
                    <p>负责人: <span th:text="${task.owner != null ? task.owner.realName : '未指定'}">负责人</span></p>
                </div>
            </div>
            
            <!-- 团队沟通 -->
            <div class="communication-container">
                <h3>团队沟通</h3>
                <div class="message-list">
                    <div class="message-received message-item">
                        <strong>张三</strong>
                        <p>我已经安排了明天下午2点的客户会议，有人能参加吗？</p>
                        <small>今天, 9:30</small>
                    </div>
                    <div class="message-sent message-item">
                        <strong>李四</strong>
                        <p>我可以参加会议。今天准备演示文稿。</p>
                        <small>今天, 9:45</small>
                    </div>
                    <div class="message-received message-item">
                        <strong>王五</strong>
                        <p>我已经更新了价格方案，请大家审核。</p>
                        <small>今天, 10:15</small>
                    </div>
                </div>
                
                <div class="message-input mt-3">
                    <textarea class="form-control" rows="2" placeholder="输入消息..."></textarea>
                    <button class="btn btn-primary mt-2">发送</button>
                </div>
            </div>
            
            <!-- 即将举行的会议 -->
            <div class="mt-4">
                <h3>即将举行的会议</h3>
                <table class="table">
                    <thead>
                        <tr>
                            <th>主题</th>
                            <th>日期和时间</th>
                            <th>参与者</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td>团队周会</td>
                            <td>2023年7月24日 - 9:00</td>
                            <td>全体成员</td>
                        </tr>
                        <tr>
                            <td>客户演示 - 某公司</td>
                            <td>2023年7月25日 - 14:00</td>
                            <td>张三, 李四</td>
                        </tr>
                        <tr>
                            <td>销售管道评审</td>
                            <td>2023年7月26日 - 11:00</td>
                            <td>张三, 王五</td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <th:block layout:fragment="scripts">
        <script th:inline="javascript">
            document.addEventListener('DOMContentLoaded', function() {
                // 初始化团队选择器
                const teamSelect = document.getElementById('team-select');
                
                // 加载所有团队
                loadTeams();
                
                // 监听团队选择变化
                teamSelect.addEventListener('change', function() {
                    const teamId = this.value;
                    if (teamId) {
                        loadTeamData(teamId);
                    }
                });
                
                // 加载所有团队
                function loadTeams() {
                    fetch('/sales/team/api/teams')
                        .then(response => response.json())
                        .then(data => {
                            if (data.code === 200 && data.data) {
                                populateTeamOptions(data.data);
                                
                                // 如果有团队，默认加载第一个
                                if (data.data.length > 0) {
                                    teamSelect.value = data.data[0].id;
                                    loadTeamData(data.data[0].id);
                                }
                            } else {
                                console.error('Failed to load teams:', data.message);
                            }
                        })
                        .catch(error => console.error('Error loading teams:', error));
                }
                
                // 填充团队选项
                function populateTeamOptions(teams) {
                    teamSelect.innerHTML = '<option value="">选择团队</option>';
                    
                    teams.forEach(team => {
                        const option = document.createElement('option');
                        option.value = team.id;
                        option.textContent = team.name;
                        teamSelect.appendChild(option);
                    });
                }
                
                // 加载团队数据
                function loadTeamData(teamId) {
                    // 调用API获取团队详情
                    fetch(`/sales/team/api/details/${teamId}`)
                        .then(response => response.json())
                        .then(data => {
                            if (data.code === 200 && data.data) {
                                updateTeamDisplay(data.data);
                            } else {
                                console.error('Failed to load team details:', data.message);
                            }
                        })
                        .catch(error => console.error('Error loading team details:', error));
                }
                
                // 更新团队显示
                function updateTeamDisplay(data) {
                    const team = data.team;
                    const members = data.members;
                    const tasks = data.tasks;
                    
                    // 更新团队信息
                    document.querySelector('.team-card h3').textContent = team.name;
                    document.querySelector('.team-card p strong').textContent = team.leader ? team.leader.realName : '未指定';
                    
                    // 更新团队成员
                    updateTeamMembers(members);
                    
                    // 更新团队任务
                    updateTeamTasks(tasks);
                }
                
                // 更新团队成员显示
                function updateTeamMembers(members) {
                    const memberList = document.querySelector('.member-list');
                    memberList.innerHTML = '';
                    
                    members.forEach(member => {
                        const memberItem = document.createElement('div');
                        memberItem.className = 'member-item';
                        
                        // 用户头像文字（取名字首字母）
                        const initials = member.user.realName ? member.user.realName.charAt(0).toUpperCase() : '?';
                        
                        memberItem.innerHTML = `
                            <div class="member-avatar">${initials}</div>
                            <span>${member.user.realName || member.user.username} (${member.role})</span>
                        `;
                        
                        memberList.appendChild(memberItem);
                    });
                    
                    if (members.length === 0) {
                        memberList.innerHTML = '<div class="alert alert-info">暂无团队成员</div>';
                    }
                }
                
                // 更新团队任务显示
                function updateTeamTasks(tasks) {
                    const taskList = document.querySelector('.task-list');
                    const tasksContainer = taskList.querySelectorAll('.task-item');
                    
                    // 清除现有任务（保留标题）
                    Array.from(tasksContainer).forEach(item => item.remove());
                    
                    // 添加新任务
                    tasks.forEach(task => {
                        const priorityClass = getPriorityClass(task.priority);
                        const priorityText = getPriorityText(task.priority);
                        
                        const taskItem = document.createElement('div');
                        taskItem.className = 'task-item';
                        taskItem.innerHTML = `
                            <div class="task-header">
                                <span><strong>${task.name}</strong></span>
                                <span class="${priorityClass}">${priorityText}</span>
                            </div>
                            <p>截止日期: ${formatDate(task.dueDate)}</p>
                            <p>负责人: ${task.owner ? task.owner.realName : '未指定'}</p>
                        `;
                        
                        taskList.appendChild(taskItem);
                    });
                    
                    if (tasks.length === 0) {
                        const noTasks = document.createElement('div');
                        noTasks.className = 'alert alert-info';
                        noTasks.textContent = '暂无团队任务';
                        taskList.appendChild(noTasks);
                    }
                }
                
                // 获取优先级样式类
                function getPriorityClass(priority) {
                    switch (priority) {
                        case 1: return 'task-priority-high';
                        case 2: return 'task-priority-medium';
                        case 3: return 'task-priority-low';
                        default: return 'task-priority-medium';
                    }
                }
                
                // 获取优先级文本
                function getPriorityText(priority) {
                    switch (priority) {
                        case 1: return '高优先级';
                        case 2: return '中优先级';
                        case 3: return '低优先级';
                        default: return '中优先级';
                    }
                }
                
                // 格式化日期
                function formatDate(dateString) {
                    if (!dateString) return '未设置';
                    
                    const date = new Date(dateString);
                    return date.toLocaleDateString('zh-CN', {
                        year: 'numeric',
                        month: 'long',
                        day: 'numeric'
                    });
                }
                
                // 发送消息
                document.querySelector('.message-input button').addEventListener('click', function() {
                    const textarea = document.querySelector('.message-input textarea');
                    const message = textarea.value.trim();
                    
                    if (message && teamSelect.value) {
                        sendTeamMessage(teamSelect.value, message);
                        textarea.value = '';
                    }
                });
                
                // 发送团队消息
                function sendTeamMessage(teamId, message) {
                    // 这里应该调用实际的API
                    // 目前只是前端模拟
                    const messageList = document.querySelector('.message-list');
                    const messageItem = document.createElement('div');
                    messageItem.className = 'message-sent message-item';
                    
                    const now = new Date();
                    const timeString = now.toLocaleTimeString('zh-CN', {
                        hour: '2-digit',
                        minute: '2-digit'
                    });
                    
                    messageItem.innerHTML = `
                        <strong>您</strong>
                        <p>${message}</p>
                        <small>今天, ${timeString}</small>
                    `;
                    
                    messageList.appendChild(messageItem);
                    
                    // 滚动到底部
                    messageList.scrollTop = messageList.scrollHeight;
                }
            });
        </script>
    </th:block>
</body>
</html> 